package net.quanter.demo.junit5.springboot.controller;

import net.quanter.demo.junit5.springboot.vo.HttpResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/***
 * 测试springboot的controller
 * 2020-06-04
 * @author 王老实
 *
 */
@RestController
public class TestController {

    @GetMapping("/check")
    public String check() {
        return "success11";
    }

    @GetMapping("/index")
    public String index() {
        return "index";
    }

    @PostMapping("/get")
    public int get() {
        return 1;
    }

    @PostMapping("/sayHello")
    public String sayHello(String name) {
        return "hello:" + name;
    }

    @PostMapping("/testUrlPost")
    public Map<String, String> testUrlPost(ServletRequest request) {
        Map<String, String> map = new HashMap<>();
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String parameterName = parameterNames.nextElement();
            map.put(parameterName, request.getParameter(parameterName));
        }
        return map;
    }

    @PostMapping("/testHeaderAndCookie")
    public HttpResult testHeaderAndCookie(HttpServletRequest request) {
        HttpResult httpResult = new HttpResult();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            httpResult.addHeader(headerName, request.getHeader(headerName));
        }
        Cookie[] cookies = request.getCookies();
        for(Cookie cookie:cookies){
            httpResult.addCookie(cookie.getName(),cookie.getValue());
        }
        return httpResult;
    }
}
